<template>
  <div class="app-content">
    <div class="content-header">
      <Row class="header-operations">
        <Col class="main__title--top"
          >{{ 1 === type ? '总体' : '动态' }}辨识</Col
        >
      </Row>
      <Row class="header-query" type="flex" justify="space-between">
        <Col span="5">
          <Select
            v-model="projectId"
            :disabled="list.length > 0"
            placeholder="项目名称"
            label-in-value
          >
            <Option v-for="item in projects" :value="item.id" :key="item.id">
              {{ item.shortName }}
            </Option>
          </Select>
        </Col>
        <Col offset="17">
          <Button type="primary" @click="addRow">新增一行</Button>
        </Col>
      </Row>
    </div>
    <div class="content-body">
      <Table
        class="table"
        border
        disabled-hover
        :columns="columns"
        :data="list"
        no-data-text="暂无数据"
        :span-method="spanHandle"
      >
        <!-- :span-method="spanHandle" -->
        <template slot-scope="{ row, index }" slot="operation">
          <a @click="addInnerRow(row, index)">下加行</a>
          <a
            v-if="row.constructionPointId && row.riskOperationId"
            @click="initEdit(index)"
            >编辑</a
          >
          <a
            v-if="row.constructionPointId && row.riskOperationId"
            @click="initDetail(index)"
            >详情</a
          >
          <a @click="initRemoveRow(index)">删除</a>
        </template>
      </Table>
      <Row type="flex" justify="center" class="content-footer">
        <Col>
          <Button type="primary" @click="save">保存</Button>
        </Col>
        <Col offset="1">
          <Button @click="closeTab">取消</Button>
        </Col>
      </Row>
    </div>
    <Modal
      v-model="modal"
      title="工点选择"
      width="70%"
      height="70%"
      class="modal"
    >
      <div class="modal-content">
        <div class="modal-query">
          <Row type="flex" class="query--top">
            <Col span="5">
              <Input v-model="projectName" disabled />
            </Col>
            <Col span="5" offset="1">
              <Input
                placeholder="工点名称"
                v-model="workSearchModel.whereMap.name"
                clearable
              />
            </Col>
          </Row>
          <Row class="query--bottom" type="flex">
            <Col span="5">
              <Select
                v-model="workSearchModel.whereMap.riskType"
                placeholder="风险类型"
                ref="riskSelectTree"
                clearable
              >
                <Option
                  v-for="item in riskSelectTreeOptions"
                  :value="item.id"
                  :key="item.id"
                  style="display: none;"
                  >{{ item.title }}</Option
                >
                <Tree
                  :data="riskTree"
                  style="padding-left:20px"
                  @on-select-change="checkData"
                ></Tree>
              </Select>
            </Col>
            <Col span="5" offset="1">
              <Select
                v-model="workSearchModel.whereMap.distRiskGrade"
                placeholder="风险等级"
                clearable
              >
                <Option
                  v-for="item in workLevels"
                  :value="item.code"
                  :key="item.id"
                  >{{ item.name }}</Option
                >
              </Select>
            </Col>
            <Col span="3" offset="10" style="text-align: right;">
              <Button type="primary" @click="workQuery(1, 10)">查询</Button>
            </Col>
          </Row>
        </div>
        <div class="modal-table">
          <Table
            class="table"
            border
            :columns="workColumns"
            :data="workList"
            no-data-text="暂无数据"
            ref="workTable"
            @on-selection-change="workSelect"
          >
            <template slot-scope="{ row }" slot="operation">
              <a @click="initWorkDetail(row)">详情</a>
            </template>
          </Table>
          <Row type="flex" justify="center">
            <Col>
              <Page
                class="pagination"
                :current="workSearchModel.currentPage"
                :page-size="workSearchModel.pageSize"
                :total="workSearchModel.totalRecord"
                :pageSizeOpts="pageSizeOpts"
                @on-change="pageChange"
                @on-page-size-change="pageSizeChange"
                show-elevator
                show-total
                show-sizer
                transfer
              />
            </Col>
          </Row>
        </div>
      </div>

      <div slot="footer">
        <Button @click="modal = false">取消</Button>
        <Button type="primary" @click="workSave">保存</Button>
      </div>
    </Modal>
    <Modal
      v-model="riskModal"
      title="风险选择"
      width="70%"
      height="70%"
      class="modal"
    >
      <div class="modal-content">
        <div class="content-box">
          <div class="content--left">
            <Tree :data="riskTree" @on-select-change="riskTreeSelect"></Tree>
          </div>
          <div class="content--right">
            <div class="modal-query">
              <Row class="query" type="flex" justify="space-between">
                <Col span="5">
                  <Select
                    v-model="riskSearchModel.whereMap.riskCategoryId"
                    placeholder="风险类别"
                    clearable
                  >
                    <Option
                      v-for="item in riskCategories"
                      :value="item.id"
                      :key="item.id"
                      >{{ item.riskCategoryName }}</Option
                    >
                  </Select>
                </Col>
                <Col span="5" offset="1">
                  <Input
                    placeholder="风险作业名称"
                    v-model="riskSearchModel.whereMap.name"
                    clearable
                  />
                </Col>
                <Col offset="5">
                  <Button type="primary" @click="riskQuery(1, 10)">查询</Button>
                </Col>
              </Row>
            </div>
            <div class="modal-table">
              <Table
                class="table"
                border
                :columns="riskColumns"
                :data="riskList"
                no-data-text="暂无数据"
                ref="riskTable"
                @on-selection-change="riskSelect"
              >
                <template slot-scope="{ row }" slot="action">
                  <a @click="initRiskDetail(row)">详情</a>
                </template>
              </Table>
              <Row type="flex" justify="center">
                <Col>
                  <Page
                    class="pagination"
                    :current="riskSearchModel.currentPage"
                    :page-size="riskSearchModel.pageSize"
                    :total="riskSearchModel.totalRecord"
                    :pageSizeOpts="pageSizeOpts"
                    @on-change="riskPageChange"
                    @on-page-size-change="riskPageSizeChange"
                    show-elevator
                    show-total
                    show-sizer
                    transfer
                  />
                </Col>
              </Row>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer">
        <Button @click="riskModal = false">取消</Button>
        <Button type="primary" @click="riskSave">保存</Button>
      </div>
    </Modal>
    <Modal
      v-model="itemModal"
      :title="itemTitle"
      width="70%"
      height="70%"
      class="modal"
    >
      <div class="modal-content">
        <div class="app-form">
          <Form label-position="top">
            <Row type="flex" justify="space-between">
              <Col span="11">
                <FormItem label="公司名称">
                  <Input v-model.trim="itemModel.enterpriseName" disabled />
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="项目名称">
                  <Input v-model.trim="itemModel.projectName" disabled />
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-between">
              <Col span="11">
                <FormItem label="工点名称">
                  <Input
                    v-model.trim="itemModel.constructionPointName"
                    disabled
                  />
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="工点风险等级">
                  <Input
                    v-model.trim="itemModel.constructionLevelName"
                    disabled
                  />
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-between">
              <Col span="11">
                <FormItem label="起始时间">
                  <Input v-model.trim="itemModel.startTime" disabled />
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="结束时间">
                  <Input v-model.trim="itemModel.endTime" disabled />
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-between">
              <Col span="11">
                <FormItem label="是否在施">
                  <Input v-model.trim="itemModel.isWork" disabled />
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span="24">
                <FormItem label="工点描述">
                  <Input v-model.trim="itemModel.note" disabled />
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-between">
              <Col span="11">
                <FormItem label="作业风险名称">
                  <Input v-model.trim="itemModel.riskName" disabled />
                </FormItem>
              </Col>

              <Col span="11">
                <FormItem label="作业风险类型">
                  <Select
                    v-model="itemModel.riskCategoryIds"
                    multiple
                    :disabled="itemDetail"
                  >
                    <Option
                      v-for="item in riskCategories"
                      :value="item.id"
                      :key="item.id"
                      >{{ item.riskCategoryName }}</Option
                    >
                  </Select>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-between">
              <Col span="11">
                <FormItem label="作业风险等级">
                  <Select v-model="itemModel.riskLevel" :disabled="itemDetail">
                    <Option
                      v-for="item in riskLevels"
                      :value="item.value"
                      :key="item.value"
                      >{{ item.text }}</Option
                    >
                  </Select>
                </FormItem>
              </Col>

              <Col span="11">
                <FormItem label="分级方法">
                  <Select
                    v-model="itemModel.classificationMethodId"
                    :disabled="itemDetail"
                  >
                    <Option
                      v-for="item in methods"
                      :value="item.id"
                      :key="item.id"
                      >{{ item.classificationMethodName }}</Option
                    >
                  </Select>
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span="24">
                <FormItem label="具体风险描述">
                  <Input
                    type="textarea"
                    v-model="itemModel.riskDescription"
                    :disabled="itemDetail"
                    maxlength="500"
                  />
                </FormItem>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
      <div slot="footer">
        <Button @click="itemModal = false">取消</Button>
        <Button type="primary" @click="singleSave" v-if="!itemDetail"
          >保存</Button
        >
      </div>
    </Modal>

    <Modal
      v-model="workDetailModal"
      title="工点详情"
      width="70%"
      height="70%"
      class="modal"
    >
      <div class="modal-content">
        <div class="app-form">
          <Form label-position="top">
            <Row type="flex" justify="space-between">
              <Col span="11">
                <FormItem label="项目名称">
                  <Input v-model.trim="workDetailModel.projectName" disabled />
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="编号">
                  <Input v-model.trim="workDetailModel.code" disabled />
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-between">
              <Col span="11">
                <FormItem label="名称">
                  <Input v-model.trim="workDetailModel.name" disabled />
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="风险类型">
                  <Input v-model.trim="workDetailModel.riskTypeName" disabled />
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-between">
              <Col span="11">
                <FormItem label="风险等级">
                  <Input
                    v-model.trim="workDetailModel.distRiskGradeName"
                    disabled
                  />
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="开始时间">
                  <Input v-model.trim="workDetailModel.startTime" disabled />
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-between">
              <Col span="11">
                <FormItem label="结束时间">
                  <Input v-model.trim="workDetailModel.endTime" disabled />
                </FormItem>
              </Col>
            </Row>

            <Row>
              <Col span="24">
                <FormItem label="描述备注">
                  <Input
                    type="textarea"
                    v-model.trim="workDetailModel.note"
                    disabled
                  />
                </FormItem>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
      <div slot="footer">
        <Button @click="workDetailModal = false">取消</Button>
      </div>
    </Modal>

    <Modal
      v-model="riskDetailModal"
      title="风险详情"
      width="70%"
      height="70%"
      class="modal"
    >
      <div class="modal-content">
        <div class="app-form">
          <Form label-position="top">
            <Row type="flex" justify="space-between">
              <Col span="11">
                <FormItem label="作业风险">
                  <Input v-model.trim="riskDetailModel.name" disabled />
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="风险类别">
                  <Input
                    v-model.trim="riskDetailModel.riskCategoryNames"
                    disabled
                  />
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-between">
              <Col span="11">
                <FormItem label="作业分级">
                  <Input v-model.trim="riskDetailModel.riskLevel" disabled />
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="分级方法">
                  <Input
                    v-model.trim="riskDetailModel.classificationMethodName"
                    disabled
                  />
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-between">
              <Col span="11">
                <FormItem label="来源">
                  <Input v-model.trim="riskDetailModel.origin" disabled />
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span="24">
                <FormItem label="备注">
                  <Input
                    v-model.trim="riskDetailModel.riskDescription"
                    disabled
                  />
                </FormItem>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
      <div slot="footer">
        <Button @click="riskDetailModal = false">取消</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
export default {
  name: 'risk-identification-add',
  props: ['type', 'project'],
  data() {
    return {
      pageSizeOpts: [10, 20, 50, 100],
      riskSelectTreeOptions: [],
      methods: [],
      singleEditIndex: null,
      riskModal: false,
      itemModel: {},
      itemModal: false,
      itemDetail: true,
      riskTree: [],
      workDetailModel: {},
      workDetailModal: false,
      riskDetailModal: false,
      riskDetailModel: {},
      workColumns: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          width: 70,
          align: 'center',
          title: '序号',
          render: (h, params) => {
            return h(
              'span',
              this.workSearchModel.pageSize *
                (this.workSearchModel.currentPage - 1) +
                params.index +
                1
            )
          }
        },
        {
          title: '名称',
          align: 'center',
          key: 'name'
        },
        {
          title: '风险等级',
          align: 'center',
          key: 'distRiskGradeName'
        },
        {
          title: '开始时间',
          align: 'center',
          key: 'startTime'
        },
        {
          title: '结束时间',
          align: 'center',
          key: 'endTime'
        },
        {
          title: '操作',
          slot: 'operation',
          align: 'center',
          className: 'table--operation'
        }
      ],
      riskColumns: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '序号',
          align: 'center',
          width: 70,
          render: (h, params) => {
            return h(
              'span',
              this.riskSearchModel.pageSize *
                (this.riskSearchModel.currentPage - 1) +
                params.index +
                1
            )
          }
        },
        {
          title: '风险作业',
          key: 'name',
          align: 'center'
        },
        {
          title: '风险类别',
          key: 'riskCategoryNames',
          align: 'center'
        },
        {
          title: '操作',
          width: 70,
          align: 'center',
          slot: 'action'
        }
      ],
      workList: [],
      riskList: [],
      projectName: '',
      currentRow: null,
      modal: false,
      // 风险类型
      riskCategories: [],
      // 风险等级
      riskLevels: [
        { text: 'I级', value: '1' },
        { text: 'II级', value: '2' },
        { text: 'III级', value: '3' },
        { text: 'IV级', value: '4' }
      ],
      workLevels: [],
      needMergeArr: [
        'constructionPointName',
        'constructionLevelName',
        'isWork'
      ], // 有合并项的列
      // rowMergeArrs: {}, // 包含需要一个或多个合并项信息的对象
      list: [],
      projects: [],
      workSelections: [],
      riskSelections: [],
      riskDisabled: [],
      columns: [
        {
          type: 'index',
          width: 70,
          align: 'center',
          title: '序号'
        },
        {
          title: '工点名称',
          key: 'constructionPointName',
          align: 'center',
          render: (h, params) => {
            const row = params.row
            const temp = row.constructionPointId
              ? [
                  h(
                    'div',
                    {
                      style: {
                        display: 'flex',
                        justifyContent: 'center',
                        alignItems: 'center'
                      }
                    },
                    [
                      h(
                        'span',
                        {
                          style: {
                            marginRight: '5px'
                          }
                        },
                        params.row.constructionPointName
                      ),
                      h(
                        'Icon',
                        {
                          style: {
                            fontSize: '14px',
                            marginBottom: '2px',
                            color: '#EE4044'
                          },
                          props: {
                            type: 'ios-remove-circle-outline'
                          },
                          on: {
                            click: () => {
                              this.batchRemove(params.index)
                            }
                          }
                        },
                        params.row.constructionPointName
                      )
                    ]
                  )
                ]
              : [
                  h(
                    'span',
                    {
                      style: {
                        color: '#0099FF',
                        fontSize: '13px',
                        cursor: 'pointer'
                      },
                      on: {
                        click: () => {
                          this.initSelectWork(params.index)
                        }
                      }
                    },
                    '选择内容'
                  )
                ]

            return h('div', temp)
          }
        },
        {
          title: '工点风险等级',
          key: 'constructionLevelName',
          align: 'center'
        },
        {
          title: '是否在施',
          key: 'isWork',
          align: 'center'
        },
        {
          title: '作业风险名称',
          key: 'riskName',
          align: 'center',
          render: (h, params) => {
            const row = params.row
            const temp = row.riskOperationId
              ? [
                  h(
                    'span',
                    {
                      style: {}
                    },
                    params.row.riskName
                  )
                ]
              : [
                  h(
                    'span',
                    {
                      style: {
                        color: '#0099FF',
                        fontSize: '13px',
                        cursor: 'pointer'
                      },
                      on: {
                        click: () => {
                          this.initSelectRisk(params.index)
                        }
                      }
                    },
                    '选择内容'
                  )
                ]

            return h('div', temp)
          }
        },
        {
          title: '作业风险类别',
          align: 'center',
          width: 125,
          key: 'riskCategoryIds',
          render: (h, params) => {
            return h(
              'Select',
              {
                props: {
                  value: params.row.riskCategoryIds,
                  size: 'small',
                  transfer: true,
                  multiple: true
                },
                on: {
                  'on-change': e => {
                    this.list[params.row._index].riskCategoryIds = e
                  }
                }
              },
              this.riskCategories.map(item => {
                return h('Option', {
                  props: {
                    value: item.id,
                    label: item.riskCategoryName
                  }
                })
              })
            )
          }
        },
        {
          title: '作业风险等级',
          align: 'center',
          key: 'riskLevel',
          render: (h, params) => {
            return h(
              'Select',
              {
                props: {
                  value: params.row.riskLevel,
                  size: 'small',
                  transfer: true
                },
                on: {
                  'on-change': e => {
                    this.list[params.row._index].riskLevel = e
                  }
                }
              },
              this.riskLevels.map(item => {
                return h('Option', {
                  props: {
                    value: item.value,
                    label: item.text
                  }
                })
              })
            )
          }
        },
        {
          title: '分级方法',
          align: 'center',
          key: 'classificationMethodId',
          render: (h, params) => {
            return h(
              'Select',
              {
                props: {
                  value: params.row.classificationMethodId,
                  size: 'small',
                  transfer: true
                },
                on: {
                  'on-change': e => {
                    this.list[params.row._index].classificationMethodId = e
                  }
                }
              },
              this.methods.map(item => {
                return h('Option', {
                  props: {
                    value: item.id,
                    label: item.classificationMethodName
                  }
                })
              })
            )
          }
        },
        {
          title: '操作',
          slot: 'operation',
          align: 'center',
          width: 110,
          className: 'table--operation'
        }
      ],
      // 工点选择查询参数
      workSearchModel: {
        currentPage: 1,
        pageSize: 10,
        whereMap: {
          projectId: '',
          name: '',
          professionalType: '',
          riskType: '',
          distRiskGrade: ''
        }
      },
      // 风险查询参数
      riskSearchModel: {
        currentPage: 1,
        pageSize: 10,
        whereMap: {
          parentId: '',
          riskCategoryId: '',
          name: ''
        }
      },
      timer: null,
      projectId: null
    }
  },
  computed: {
    itemTitle() {
      return this.itemDetail ? '辨识详情' : '风险编辑'
    },
    rowMergeArrs() {
      return this.rowMergeHandle(this.needMergeArr, this.list)
    }
  },
  methods: {
    ...mapMutations(['closeTag']),
    init() {
      this.initProjects()
      this.initRiskCategories()
      this.initWorkLevel()
      this.initRiskTypeTree()
      this.initMethods()
    },
    //获取项目列表
    initProjects() {
      this.projectId = this.project
      this.$api.riskIdentification.queryProjectsForBusiness().then(res => {
        if (res.code === 200) {
          this.projects = res.data
          this.projects = Object.freeze(this.projects)
          this.projectName = this.projects.find(
            p => p.id === this.projectId
          ).shortName
        } else {
          this.$Message.warning(res.message)
        }
      })
    },
    // 获取风险类型
    initRiskCategories() {
      this.$api.measuresLibrary
        .getRiskCategoryFindAll()
        .then(({ code, data }) => {
          if (code === 200) {
            this.riskCategories = data
            this.riskCategories = Object.freeze(this.riskCategories)
          }
        })
    },
    // 获取工点风险等级
    initWorkLevel() {
      this.$api.UnitProject.getListByTypeCode('RISK_GRADE').then(resp => {
        if (resp.code == 200) {
          this.workLevels = resp.data
          this.workLevels = Object.freeze(this.workLevels)
        } else {
          this.$Message.warning(resp.message)
        }
      })
    },
    // 获取风险类型树
    initRiskTypeTree() {
      //树
      this.$api.measuresLibrary
        .getQueryRiskTypeTree()
        .then(({ code, data, message }) => {
          if (code === 200) {
            const handle = nodes => {
              nodes.forEach(node => {
                this.$set(node, 'title', node.name)
                this.$set(node, 'expand', false)
                if (node.children.length > 0) {
                  handle(node.children)
                }
              })
            }
            handle(data)
            this.riskTree = data
            this.riskTree = Object.freeze(this.riskTree)
          } else {
            this.$Message.error(message)
          }
        })
    },
    //分级方法
    initMethods() {
      this.$api.measuresLibrary
        .getRiskOperationClassificationMethod()
        .then(({ code, data, message }) => {
          if (code === 200) {
            this.methods = data
            this.methods = Object.freeze(this.methods)
          } else {
            this.$Message.error(message)
          }
        })
    },
    getTree(tree) {
      return tree.map(node => {
        node.title = node.name
        if (node.hasChildren) {
          node.loading = false
          node.children = []
        }
        return node
      })
    },
    pageChange(page) {
      this.workQuery(page, this.workSearchModel.pageSize)
    },
    pageSizeChange(size) {
      this.workQuery(this.workSearchModel.currentPage, size)
    },
    workQuery(page, size) {
      this.workSearchModel.currentPage = page || 1
      this.workSearchModel.pageSize = size || 10
      this.workSelections = []
      this.$api.WorkstationLedger.workstationLedgerList(
        this.workSearchModel
      ).then(({ code, data, message }) => {
        if (200 === code) {
          this.workList = data.resultObject
          this.workList = Object.freeze(this.workList)
          this.workSearchModel.totalRecord = data.totalRecord
        } else {
          this.$Message.error(message)
        }
      })
    },
    checkData(selections, current) {
      this.riskSelectTreeOptions = [current]
      this.workSearchModel.whereMap.riskType = current.id
      this.$refs.riskSelectTree.visible = false
    },
    riskTreeSelect(nodes, node) {
      this.riskSearchModel.whereMap.parentId = node.id
      this.riskQuery()
    },
    riskPageChange(page) {
      this.riskQuery(page, this.riskSearchModel.pageSize)
    },
    riskPageSizeChange(size) {
      this.riskQuery(this.riskSearchModel.currentPage, size)
    },
    riskQuery(page = 1, size = 10) {
      this.riskSearchModel.currentPage = page
      this.riskSearchModel.pageSize = size
      this.riskSelections = []
      this.$api.measuresLibrary
        .getRiskInfoLibPageList(this.riskSearchModel)
        .then(({ code, data, message }) => {
          if (200 === code) {
            this.riskList = Object.freeze(
              data.resultObject.map(r => {
                return { ...r, _disabled: this.riskDisabled.indexOf(r.id) > -1 }
              })
            )
            this.riskSearchModel.totalRecord = data.totalRecord
          } else {
            this.$Message.error(message)
          }
        })
    },
    workSelect(selection) {
      this.workSelections = selection
    },
    riskSelect(selection) {
      this.riskSelections = selection
    },
    // 选择工点保存
    workSave() {
      if (this.workSelections.length > 0) {
        // 关闭modal
        this.modal = false
        // 存放临时结果
        let works = []
        // 临时作业类型id
        let tempTypeId = null
        // 临时作业风险对应的作业列表
        let tempRisks = null
        // 临时组装结果
        let tempResult = null
        // 选择的工点数组提取出来的所有作业风险类型id（工点下可能配置有一样的）
        let typeIds = Array.from(
          new Set(this.workSelections.map(w => w.riskType).filter(t => t))
        )
        // 如果类型id不为空，说明有对应的作业列表，查询后组装，没有直接处理添加
        if (typeIds.length > 0) {
          this.$api.riskIdentification
            .queryRiskByTypes(typeIds)
            .then(({ code, data, message }) => {
              if (200 === code) {
                this.workSelections.forEach(w => {
                  tempTypeId = w.riskType
                  tempRisks = tempTypeId
                    ? data[tempTypeId].length > 0
                      ? data[tempTypeId]
                      : [{}]
                    : [{}]
                  tempResult = Object.freeze(
                    tempRisks.map(d => {
                      return {
                        constructionPointId: w.id,
                        constructionPointName: w.name,
                        constructionLevelName: w.distRiskGradeName,
                        enterpriseName: w.enterpriseName,
                        projectName: w.projectName,
                        startTime: w.startTime,
                        endTime: w.endTime,
                        note: w.note,
                        isWork: w.work ? '是' : '否',
                        riskCategoryIds: d.riskCategoryIds
                          ? d.riskCategoryIds.split(',')
                          : [],
                        riskOperationId: d.id,
                        riskName: d.name,
                        riskLevel: d.riskLevel,
                        classificationMethodId: d.classificationMethodId,
                        riskDescription: d.riskDescription
                      }
                    })
                  )
                  works = Object.freeze([...works, ...tempResult])
                  tempRisks = null
                  tempResult = null
                })
                /**
                 * ! 1.双层for循环遍历workSelections和对应的riskList组装数据，20条页       面开始卡顿，去除双层循环不卡顿；
                 * ! 2.改为单层for循环处理，map之后返回，最后统一添加，发现卡顿依旧，怀疑list数据多时（内存有数组），vue的监听造成页面卡顿；
                 * ! 3.将list冻结，页面不卡顿。
                 */
                // this.list.splice(this.currentRow, 1, ...works)
                const start = this.list.slice(0, this.currentRow)
                const end = this.list.slice(this.currentRow + 1)
                this.list = [...start, ...works, ...end]
                this.list = Object.freeze(this.list)
                works = []
              } else {
                this.$Message.error(message)
              }
            })
        } else {
          this.workSelections.forEach(w => {
            works.push({
              constructionPointId: w.id,
              constructionPointName: w.name,
              constructionLevelName: w.distRiskGradeName,
              enterpriseName: w.enterpriseName,
              projectName: w.projectName,
              startTime: w.startTime,
              endTime: w.endTime,
              note: w.note,
              isWork: w.work ? '是' : '否',
              riskCategoryIds: [],
              riskOperationId: '',
              riskName: '',
              riskLevel: '',
              classificationMethodId: '',
              riskDescription: ''
            })
          })
          const start = this.list.slice(0, this.currentRow)
          const end = this.list.slice(this.currentRow + 1)
          this.list = Object.freeze([...start, ...works, ...end])
          works = []
        }
      } else {
        this.$Message.error('请至少选择一项')
      }
    },
    riskSave() {
      if (this.riskSelections.length === 0) {
        this.$Message.error('请至少选择一项')
        return
      }
      if (this.riskSelections.length === 1) {
        const temp = this.riskSelections[0]
        let copy = JSON.parse(JSON.stringify(this.list[this.currentRow]))
        copy.riskOperationId = temp.id
        copy.riskCategoryIds = temp.riskCategoryIds
          ? temp.riskCategoryIds.split(',')
          : []
        copy.riskLevel = temp.riskLevel
        copy.riskName = temp.name
        copy.classificationMethodId = temp.classificationMethodId
        copy.riskDescription = temp.riskDescription
        const start = this.list.slice(0, this.currentRow)
        const end = this.list.slice(this.currentRow + 1)
        this.list = [...start, copy, ...end]
        this.list = Object.freeze(this.list)
      } else {
        let risks = []
        const row = this.list[this.currentRow]
        this.riskSelections.forEach(r => {
          let copy = {
            constructionPointId: row.constructionPointId,
            constructionPointName: row.constructionPointName,
            constructionLevelName: row.constructionLevelName,
            enterpriseName: row.enterpriseName,
            projectName: row.projectName,
            startTime: row.startTime,
            endTime: row.endTime,
            isWork: row.isWork,
            note: row.note,
            riskCategoryIds: r.riskCategoryIds
              ? r.riskCategoryIds.split(',')
              : [],
            riskOperationId: r.id,
            riskName: r.name,
            riskLevel: r.riskLevel,
            classificationMethodId: r.classificationMethodId,
            riskDescription: r.riskDescription
          }
          risks.push(copy)
        })
        const start = this.list.slice(0, this.currentRow)
        const end = this.list.slice(this.currentRow + 1)
        this.list = [...start, ...risks, ...end]
        this.list = Object.freeze(this.list)
        // this.list.splice(this.currentRow, 1, ...risks)
      }
      this.riskModal = false
    },
    addRow() {
      // 新增的时候首先判断有没有选择项目
      if (!this.projectId) {
        this.$Message.error('请选择项目')
        return
      }
      // 其次判断list有没有东西，有的话全部校验，因为内层是可以多增的，所以不能只校验最后一个
      const count = this.list.length
      if (count > 0) {
        const errors = this.list.filter(l => {
          return (
            !l.constructionPointId ||
            l.riskCategoryIds.length === 0 ||
            !l.riskOperationId ||
            !l.classificationMethodId ||
            !l.riskLevel
          )
        })
        if (errors.length > 0) {
          this.$Message.error('列表信息不完整，请完善')
          return
        }
      }
      const row = {
        // 工点id
        constructionPointId: '',
        // 工点名字
        constructionPointName: '',
        constructionLevelName: '',
        isWork: '',
        // 风险类别id
        riskCategoryIds: [],
        // 作业风险id
        riskOperationId: '',
        riskName: '',
        // 作业风险等级
        riskLevel: '',
        // 分级方法id
        classificationMethodId: '',
        riskDescription: ''
      }
      // this.list.push(row)
      this.list = [...this.list, row]
      this.list = Object.freeze(Object.freeze(this.list))
    },
    addInnerRow(row, index) {
      let copy = JSON.parse(JSON.stringify(row))
      copy.riskOperationId = ''
      copy.riskCategoryIds = []
      copy.riskName = ''
      copy.riskLevel = ''
      copy.classificationMethodId = ''
      const start = this.list.slice(0, index + 1)
      const end = this.list.slice(index + 1)
      // this.list.splice(index + 1, 0, copy)
      this.list = Object.freeze([...start, copy, ...end])
    },
    initSelectWork(index) {
      this.workSearchModel = {
        currentPage: 1,
        pageSize: 10,
        whereMap: {
          projectId: this.projectId,
          name: '',
          professionalType: '',
          riskType: '',
          distRiskGrade: ''
        }
      }
      this.workSelections = []
      this.modal = true
      this.workQuery()
      this.currentRow = index
    },
    initSelectRisk(index) {
      const workId = this.list[index].constructionPointId
      if (!workId) {
        this.$Message.error('请先选择工点')
        return
      }
      this.riskSearchModel = {
        currentPage: 1,
        pageSize: 10,
        whereMap: {
          parentId: '',
          riskCategoryId: '',
          name: ''
        }
      }
      this.riskSelections = []
      this.riskList = []
      this.currentRow = index
      //  同时记录禁选的风险，也就是已经存在的风险
      this.riskDisabled = Object.freeze(
        this.list
          .filter(l => l.constructionPointId === workId)
          .map(s => s.riskOperationId)
      )
      console.log('risk disable: ', this.riskDisabled)
      this.riskModal = true
    },
    // eslint-disable-next-line no-unused-vars
    spanHandle({ row, column, rowIndex, columnIndex }) {
      const prop = column.key
      if (this.needMergeArr.indexOf(prop) > -1)
        return this.mergeAction(prop, rowIndex, column)
    },
    // eslint-disable-next-line no-unused-vars
    mergeAction(val, rowIndex, colData) {
      const mergeRow = this.rowMergeArrs[val]
      if (mergeRow && mergeRow.rowArr) {
        let _row = this.rowMergeArrs[val].rowArr[rowIndex]
        let _col = _row > 0 ? 1 : 0
        return [_row, _col]
      } else {
        return [1, 1]
      }
    },
    rowMergeHandle(arr, data) {
      if (!Array.isArray(arr) && !arr.length) return false
      if (!Array.isArray(data) && !data.length) return false
      let needMerge = {}
      arr.forEach(i => {
        needMerge[i] = {
          rowArr: [],
          rowMergeNum: 0
        }
        data.forEach((item, index) => {
          if (index === 0) {
            needMerge[i].rowArr.push(1)
            needMerge[i].rowMergeNum = 0
          } else {
            if (item[i] === data[index - 1][i]) {
              needMerge[i].rowArr[needMerge[i].rowMergeNum] += 1
              needMerge[i].rowArr.push(0)
            } else {
              needMerge[i].rowArr.push(1)
              needMerge[i].rowMergeNum = index
            }
          }
        })
      })
      return needMerge
    },
    batchRemove(index) {
      this.$Modal.confirm({
        title: '删除提示',
        content: '<p>确认删除此工点吗？</p>',
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          let temp = 0
          let item = null
          const id = this.list[index].constructionPointId
          for (let i = index, l = this.list.length; i < l; i++) {
            item = this.list[i]
            if (id !== item.constructionPointId) {
              temp = i
              break
            }
          }
          if (!temp) temp = this.list.length + 1
          const start = this.list.slice(0, index)
          const end = this.list.slice(temp)
          this.list = [...start, ...end]
          this.list = Object.freeze(this.list)
          // this.list.splice(index, 1)
        }
      })
    },
    initRemoveRow(index) {
      this.$Modal.confirm({
        title: '删除提示',
        content: '<p>确认删除当前项吗？</p>',
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          const start = this.list.slice(0, index)
          const end = this.list.slice(index + 1)
          this.list = [...start, ...end]
          this.list = Object.freeze(this.list)
          // this.list.splice(index, 1)
        }
      })
    },
    initDetail(index) {
      this.itemModel = this.list[index]
      this.itemDetail = true
      this.itemModal = true
    },
    initEdit(index) {
      this.itemModel = JSON.parse(JSON.stringify(this.list[index]))
      this.singleEditIndex = index
      this.itemDetail = false
      this.itemModal = true
    },
    singleSave() {
      let current = this.list[this.singleEditIndex]
      current.riskCategoryIds = this.itemModel.riskCategoryIds
      current.riskLevel = this.itemModel.riskLevel
      current.classificationMethodId = this.itemModel.classificationMethodId
      current.riskDescription = this.itemModel.riskDescription
      const start = this.list.slice(0, this.singleEditIndex)
      const end = this.list.slice(this.singleEditIndex + 1)
      this.list = Object.freeze([...start, current, ...end])
      this.itemModal = false
    },
    initWorkDetail(data) {
      this.workDetailModel = data
      this.workDetailModal = true
    },
    initRiskDetail(data) {
      this.riskDetailModel = data
      this.riskDetailModal = true
    },
    save() {
      // 校验
      if (!this.projectId) {
        this.$Message.error('未选择项目')
        return
      }
      if (this.list.length === 0) {
        this.$Message.error('列表不能为空')
        return
      } else {
        const errors = this.list.filter(l => {
          return (
            !l.constructionPointId ||
            !l.constructionPointId ||
            l.riskCategoryIds.length === 0 ||
            !l.riskOperationId ||
            !l.classificationMethodId ||
            !l.riskLevel
          )
        })
        if (errors.length > 0) {
          this.$Message.error('列表信息不完整，请完善')
          return
        }
      }
      // 数据处理
      let result = {
        projectId: this.projectId,
        constructionPointInfoList: [],
        flag: this.type
      }
      let mapper = {}
      let item = {}
      this.list.forEach(l => {
        if (!(l.constructionPointId in mapper)) {
          mapper[l.constructionPointId] = []
        }
        item = {
          riskOperationId: l.riskOperationId,
          riskCategoryIds: l.riskCategoryIds.join(','),
          riskLevel: l.riskLevel,
          classificationMethodId: l.classificationMethodId,
          riskDescription: l.riskDescription
        }
        mapper[l.constructionPointId].push(item)
      })
      const keys = Object.keys(mapper)
      for (let key of keys) {
        result.constructionPointInfoList.push({
          constructionPointId: key,
          riskInfoList: mapper[key]
        })
      }
      this.$api.riskIdentification.save(result).then(({ code, message }) => {
        if (200 === code) {
          this.$Message.success('新增成功')
          this.closeTag({
            name: 'risk-identification-add',
            params: { ...this.$route.params },
            query: { ...this.$route.query }
          })
        } else {
          this.$Message.error(message)
        }
      })
    },
    closeTab() {
      this.closeTag({
        name: 'risk-identification-add',
        params: { ...this.$route.params },
        query: { ...this.$route.query }
      })
    }
  },
  mounted() {
    this.init()
  },
  beforeDestroy() {
    console.log(this.$vnode)
  }
}
</script>

<style></style>
